package tuding.android.bigplanettracks.maps.tuding;

import java.io.File;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import tuding.android.bigplanettracks.maps.MarkerManager;
import tuding.android.bigplanettracks.maps.db.DAO;
import tuding.android.bigplanettracks.maps.db.GeoBookmark;
import tuding.android.bigplanettracks.maps.storage.SQLLocalStorage;
import tuding.android.bigplanettracks.maps.ui.AddBookmarkDialog;
import tuding.android.bigplanettracks.maps.ui.AddNotesDialog;
import tuding.android.bigplanettracks.maps.ui.MapControl;
import tuding.android.bigplanettracks.maps.ui.OnDialogClickListener;
import tuding.android.bigplanettracks.tracks.MyTimeUtils;
import tuding.android.bigplanettracks.tracks.listview.IconAdapter;
import tuding.android.bigplanettracks.BigPlanet;
import tuding.android.bigplanettracks.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class InfoWindow extends RelativeLayout{
	RelativeLayout infowin = null;
	
	public static final NumberFormat LAT_LONG_FORMAT =
      new DecimalFormat("##,###.0000");
	public static final NumberFormat ALTITUDE_FORMAT =
      new DecimalFormat("###,###");
	public static final NumberFormat SPEED_FORMAT =
      new DecimalFormat("###,###.0");
	public static final NumberFormat DISTANCE_FORMAT =
	      new DecimalFormat("###,###.00");

	
	public static float STATS_maxspeed = 0;
	public static float STATS_maxalt = 0;
	public static int STATS_totalrise = 0;
	public static int STATS_totalfall = 0;
	public static int STATS_totaldistance = 0;
	public static long STATS_totaltime = 0;
	
	public static void resetSTATS() {
		STATS_maxspeed = 0;
		STATS_maxalt = 0;
		STATS_totalrise = 0;
		STATS_totalfall = 0;
		STATS_totaldistance = 0;
		STATS_totaltime = 0;
	}
	
	
	// for bookmark
	public InfoWindow(final Context context, DAO bookmarkDAO, final long markerID, final ViewGroup parent) {
		super(context);
		infowin = new RelativeLayout(context);
		final GeoBookmark bookmark = bookmarkDAO.getBookmarkByID(markerID);
		bookmarkDAO.close();
		View v = View.inflate(context, R.layout.infowindow, parent );
		final TextView notesValue= (TextView) v.findViewById(R.id.actionNotesText);
		final Button   editBtn   = (Button) v.findViewById(R.id.EditBtn);
		final Button   delBtn    = (Button) v.findViewById(R.id.DelBtn);
		final ImageView iconView = (ImageView) v.findViewById(R.id.actionTypeIcon);
		iconView.setImageResource(R.drawable.bookmark);
		String tmp_text = bookmark.getName();
        tmp_text += (bookmark.getDescription() == "")?"":("\n"+bookmark.getDescription());
		notesValue.setText(tmp_text);
		editBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				((MapControl) parent).clearInfoWin();
				AddBookmarkDialog.show(context, bookmark, new OnDialogClickListener() {
					@Override
					public void onCancelClick() {
					}
					
					@Override
					public void onOkClick(Object obj) {
						DAO d = new DAO(context);
						d.updateGeoBookmark(bookmark);
					}
		        }); 
			} 
	    });
		
		delBtn.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
				new AlertDialog.Builder(context).setTitle(R.string.REMOVE_BOOKMARK_TITLE)
				.setMessage(R.string.REMOVE_BOOKMARK_MESSAGE)
				.setPositiveButton(R.string.YES_LABEL,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								((MapControl) parent).clearInfoWin();
								DAO d = new DAO(context);
								d.removeGeoBookmark(bookmark.getId());
								if(!MarkerManager.removeMarker(MarkerManager.markers, 0, bookmark.getId())){
								}
								
							}
						})
				.setNegativeButton(R.string.NO_LABEL, null).show();
			} }
		);
	}
	
	
	// for actions
	public InfoWindow(final Context context, ActionNotes actionN, final int actionType, final long actionID, int width, final ViewGroup parent) {
		super(context);
		infowin = new RelativeLayout(context);
		Log.i("TAP", "getInfoWindow: actionN:"+actionN.toString()+" actionType "+actionType+" actionID "+actionID+" width "+width);
		if(actionType == MarkerManager.ACTION_TYPE_NOTES) {
			final ActionBase actionB = actionN.getActionNotesByID(actionID);
			actionN.close();
			//DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date date = new Date(actionB.getDate());
			
			
			View v = View.inflate(context, R.layout.infowindow, parent );
			final TextView datelocValue = (TextView) v.findViewById(R.id.actionTimeLocText);
			final TextView notesValue= (TextView) v.findViewById(R.id.actionNotesText);
			final TextView etcValues = (TextView) v.findViewById(R.id.actionEtcText);
			final Button   editBtn   = (Button) v.findViewById(R.id.EditBtn);
			final Button   delBtn    = (Button) v.findViewById(R.id.DelBtn);
			final ImageView iconView = (ImageView) v.findViewById(R.id.actionTypeIcon);
			iconView.setImageResource(R.drawable.notes36);
			String tmp_text = context.getString(R.string.ShiJian)+df.format(date)+" "+context.getString(R.string.WeiZhi)+String.valueOf(actionB.getLat())+" "+String.valueOf(actionB.getLon());
			datelocValue.setText(tmp_text);
			Log.i("TAP", "dateValue "+datelocValue.getText());
            tmp_text = actionB.getName();
            tmp_text += (actionB.getDescription() == "")?"":("\n"+actionB.getDescription());
			notesValue.setText(tmp_text);
			Log.i("TAP", "notesValue "+tmp_text);
			tmp_text = context.getString(R.string.SuDu)+actionB.getSpeed()+"m/s\n"+context.getString(R.string.GaoDu)+actionB.getAltitude()+"m";
			etcValues.setText(tmp_text);
			editBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					((MapControl) parent).clearInfoWin();
					AddNotesDialog.show(context, actionB, new OnDialogClickListener() {
						@Override
						public void onCancelClick() {
						}
						
						@Override
						public void onOkClick(Object obj) {
							ActionNotes d = new ActionNotes(context);
							d.updateActionNotes(actionB);
						}
			        }); 
				} 
		    });
			
			delBtn.setOnClickListener( new OnClickListener() {
				public void onClick(View v) {
					new AlertDialog.Builder(context).setTitle(R.string.REMOVE_ACTIONNOTES_TITLE)
					.setMessage(R.string.REMOVE_BOOKMARK_MESSAGE)
					.setPositiveButton(R.string.YES_LABEL,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									((MapControl) parent).clearInfoWin();
									ActionNotes d = new ActionNotes(context);
									d.removeActionNotes(actionB.getId());
									BigPlanet.DBAdapter.open();
									BigPlanet.DBAdapter.removeActionMarker(actionType, actionID);
									int tmp_cnt = 0;
									if(BigPlanet.isGPSTracking){
										if(!MarkerManager.removeMarker(MarkerManager.markersG, actionType, actionID)){
											tmp_cnt++;
										}
									} else {
										if(!MarkerManager.removeMarker(MarkerManager.markersDB, actionType, actionID)){
											tmp_cnt++;
										}
									}
									if(!MarkerManager.removeMarker(MarkerManager.savedTrackG, actionType, actionID)){
										tmp_cnt++;
									}
									if(tmp_cnt == 2) // means markers should not be on the screan
										Toast.makeText(context, context.getString(R.string.DEL_FAIL), Toast.LENGTH_SHORT).show();
								}
							})
					.setNegativeButton(R.string.NO_LABEL, null).show();
				} }
			);
			
			
			//infowin.addView(v);
		} else if(actionType == MarkerManager.ACTION_TYPE_PHOTO) {
			final ActionBase actionB = actionN.getActionPhotoByID(actionID);
			actionN.close();
			//DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date date = new Date(actionB.getDate());
			
			
			View v = View.inflate(context, R.layout.infowindowphoto, parent );
			final TextView datelocValue = (TextView) v.findViewById(R.id.actionTimeLocText);
			final TextView notesValue= (TextView) v.findViewById(R.id.actionPhotoText);
			final TextView etcValues = (TextView) v.findViewById(R.id.actionEtcText);
			final Button   editBtn   = (Button) v.findViewById(R.id.EditBtn);
			final Button   delBtn    = (Button) v.findViewById(R.id.DelBtn);
			final ImageView photoView = (ImageView) v.findViewById(R.id.actionPhoto);
			// prepare the photo
			final String photopath = actionB.getUri();
			Bitmap smallphoto = getBitmapFromLocalPath(SQLLocalStorage.TRACK_PATH+"photo/thumbnail/thumbnail"+photopath, 1);
			
			/*
			try {
				smallphoto = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(photopath));
			} catch (Exception e){
				e.printStackTrace();
			}
			*/
			Log.i("PHOTO", "smallphoto "+smallphoto);
			photoView.setImageBitmap(smallphoto);
			photoView.setOnClickListener(new OnClickListener() {
			    public void onClick(View v) {
			    	Dialog photoviewd = new Dialog(context);
			    	photoviewd.setCanceledOnTouchOutside(true);
			    	photoviewd.setCancelable(true);
			    	photoviewd.requestWindowFeature(Window.FEATURE_NO_TITLE);
			    	photoviewd.setContentView(R.layout.photoviewdialog);
			    	Bitmap biggerphoto = getBitmapFromLocalPath(SQLLocalStorage.TRACK_PATH+"photo/"+photopath, 1);
			    	Log.i("VIEWPHOTO", ""+SQLLocalStorage.TRACK_PATH+"photo/"+photopath +" ");
			    	ImageView biggerimage = (ImageView) photoviewd.findViewById(R.id.biggerimage);
			    	biggerimage.setImageBitmap(biggerphoto);
			    	photoviewd.show();
			     }
			 });
			String tmp_text = context.getString(R.string.ShiJian)+df.format(date)+"\n"+context.getString(R.string.WeiZhi)+String.valueOf(actionB.getLat())+" "+String.valueOf(actionB.getLon());
			datelocValue.setText(tmp_text);
			Log.i("PHOTO", "dateValue "+datelocValue.getText());
            tmp_text = actionB.getName();
            tmp_text += (actionB.getDescription() == null)?"":(" "+actionB.getDescription());
			notesValue.setText(tmp_text);
			Log.i("PHOTO", "notesValue "+tmp_text);
			tmp_text = context.getString(R.string.SuDu)+actionB.getSpeed()+"m/s  "+context.getString(R.string.GaoDu)+actionB.getAltitude()+"m";
			etcValues.setText(tmp_text);
			editBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					((MapControl) parent).clearInfoWin();
					AddNotesDialog.show(context, actionB, new OnDialogClickListener() {
						@Override
						public void onCancelClick() {
						}
						
						@Override
						public void onOkClick(Object obj) {
							ActionNotes d = new ActionNotes(context);
							d.updateActionPhoto(actionB);
						}
			        }); 
				} 
		    });
			 
			delBtn.setOnClickListener( new OnClickListener() {
				public void onClick(View v) {
					new AlertDialog.Builder(context).setTitle(R.string.REMOVE_ACTIONNOTES_TITLE)
					.setMessage(R.string.REMOVE_BOOKMARK_MESSAGE)
					.setPositiveButton(R.string.YES_LABEL,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									((MapControl) parent).clearInfoWin();
									ActionNotes d = new ActionNotes(context);
									d.removeActionPhoto(actionB.getId());
									BigPlanet.DBAdapter.open();
									BigPlanet.DBAdapter.removeActionMarker(actionType, actionID);
									removePhoto(actionB.getUri());
									removeThumbnail(actionB.getUri());
									int tmp_cnt = 0;
									if(BigPlanet.isGPSTracking){
										if(!MarkerManager.removeMarker(MarkerManager.markersG, actionType, actionID)){
											tmp_cnt++;
										}
									} else {
										if(!MarkerManager.removeMarker(MarkerManager.markersDB, actionType, actionID)){
											tmp_cnt++;
										}
									}
									if(!MarkerManager.removeMarker(MarkerManager.savedTrackG, actionType, actionID)){
										tmp_cnt++;
									}
									if(tmp_cnt == 2) // means markers should not be on the screan
										Toast.makeText(context, context.getString(R.string.DEL_FAIL), Toast.LENGTH_SHORT).show();
								}
							})
					.setNegativeButton(R.string.NO_LABEL, null).show();
				} }
			);
		}
	}
	
	
	public void UpdateStatsAccuracy(Activity activity) {
		if(BigPlanet.isOpenStatsWin) {
			TextView accv = (TextView) activity.findViewById(R.id.STATS_Accuracy);
			accv.setText(ALTITUDE_FORMAT.format(BigPlanet.currentLocation.getAccuracy()));
		}
	}
	
	public void UpdateStatsSpeed(Activity activity) {
		if(BigPlanet.isOpenStatsWin) {
			TextView rs = (TextView) activity.findViewById(R.id.STATS_realSpeed);
			rs.setText(SPEED_FORMAT.format(BigPlanet.currentLocation.getSpeed()*(3.6)));
		}
	}
	
	public void UpdateStats(Activity activity) {
		if(BigPlanet.isOpenStatsWin) {
			try {
				TextView rs = (TextView) activity.findViewById(R.id.STATS_realSpeed);
				rs.setText(SPEED_FORMAT.format(BigPlanet.currentLocation.getSpeed()*(3.6)));
				TextView hs = (TextView) activity.findViewById(R.id.STATS_maxSpeed);
				hs.setText((STATS_maxspeed==0)?activity.getString(R.string.unknown):SPEED_FORMAT.format(STATS_maxspeed*(3.6)));
				TextView altv = (TextView) activity.findViewById(R.id.STATS_realAltitude);
				altv.setText(ALTITUDE_FORMAT.format(BigPlanet.currentLocation.getAltitude()));
				TextView halt = (TextView) activity.findViewById(R.id.STATS_maxAltitude);
				halt.setText((STATS_maxalt==0)?activity.getString(R.string.unknown):ALTITUDE_FORMAT.format(STATS_maxalt));
				TextView latv = (TextView) activity.findViewById(R.id.STATS_Latitude);
				latv.setText(LAT_LONG_FORMAT.format(BigPlanet.currentLocation.getLatitude()));
				TextView lonv = (TextView) activity.findViewById(R.id.STATS_Longitude);
				lonv.setText(LAT_LONG_FORMAT.format(BigPlanet.currentLocation.getLongitude()));
				TextView accv = (TextView) activity.findViewById(R.id.STATS_Accuracy);
				accv.setText(ALTITUDE_FORMAT.format(BigPlanet.currentLocation.getAccuracy()));
				// 
			
				TextView totaldist = (TextView) activity.findViewById(R.id.STATS_totalDistance);
				totaldist.setText((STATS_totaldistance==0)?activity.getString(R.string.unknown):DISTANCE_FORMAT.format((float)STATS_totaldistance/1000));
				TextView totalrise = (TextView) activity.findViewById(R.id.STATS_totalRise);
				totalrise.setText((STATS_totalrise==0)?activity.getString(R.string.unknown):(""+STATS_totalrise));
				TextView totalfall = (TextView) activity.findViewById(R.id.STATS_totalFall);
				totalfall.setText((STATS_totalfall==0)?activity.getString(R.string.unknown):(""+STATS_totalfall));
				TextView totaltime = (TextView) activity.findViewById(R.id.STATS_totalTime);
				totaltime.setText((STATS_totaltime==0)?activity.getString(R.string.unknown):IconAdapter.getTimeString(STATS_totaltime, activity));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	public InfoWindow(final Context context, final ViewGroup parent, int type) {
		super(context);
		infowin = new RelativeLayout(context);
		View v = View.inflate(context, R.layout.infowindowreadonly, parent );
		if(type == 0) { // record marker
			//Log.i("Recording", "here");
			final ImageView iconView = (ImageView) v.findViewById(R.id.Icon);
			iconView.setImageResource(R.drawable.recording);
			final TextView thetext = (TextView) v.findViewById(R.id.A_Label);
			thetext.setText(context.getString(R.string.LASTUPLOADTIME)+MyTimeUtils.getLocalTimeStringSimple(BigPlanet.timeRecord));
		}
	}
	
	
	// for self marker
	public InfoWindow(final Context context, final ViewGroup parent) {
		super(context);
		infowin = new RelativeLayout(context);
		View v = View.inflate(context, R.layout.infowindowsimple, parent );
		
		//final ImageView iconView = (ImageView) v.findViewById(R.id.actionTypeIcon);

		
		final TextView realspeed = (TextView) v.findViewById(R.id.STATS_realSpeed);
		final TextView maxspeed  = (TextView) v.findViewById(R.id.STATS_maxSpeed);
		realspeed.setText((BigPlanet.currentLocation==null)?context.getString(R.string.unknown):(SPEED_FORMAT.format(BigPlanet.currentLocation.getSpeed()*(3.6))));
		maxspeed.setText((STATS_maxspeed==0)?context.getString(R.string.unknown):(SPEED_FORMAT.format(STATS_maxspeed*(3.6))));
		
		
		final TextView realalt   = (TextView) v.findViewById(R.id.STATS_realAltitude);
		final TextView maxalt = (TextView) v.findViewById(R.id.STATS_maxAltitude); // maybe only max is needed
		realalt.setText((BigPlanet.currentLocation==null)?context.getString(R.string.unknown):(ALTITUDE_FORMAT.format(BigPlanet.currentLocation.getAltitude())));
		maxalt.setText((STATS_maxalt==0)?context.getString(R.string.unknown):(ALTITUDE_FORMAT.format(STATS_maxalt)));
		
		final TextView lon = (TextView) v.findViewById(R.id.STATS_Longitude);
		final TextView lat = (TextView) v.findViewById(R.id.STATS_Latitude);
		lon.setText((BigPlanet.currentLocation==null)?context.getString(R.string.unknown):(LAT_LONG_FORMAT.format(BigPlanet.currentLocation.getLongitude())));
		lat.setText((BigPlanet.currentLocation==null)?context.getString(R.string.unknown):(LAT_LONG_FORMAT.format(BigPlanet.currentLocation.getLatitude())));
		
		final TextView totalrise = (TextView) v.findViewById(R.id.STATS_totalRise);
		final TextView totalfall = (TextView) v.findViewById(R.id.STATS_totalFall);
		totalrise.setText((STATS_totalrise==0)?context.getString(R.string.unknown):(""+STATS_totalrise));
		totalfall.setText((STATS_totalfall==0)?context.getString(R.string.unknown):(""+STATS_totalfall));
		
		final TextView totaldist = (TextView) v.findViewById(R.id.STATS_totalDistance);
		final TextView totaltime = (TextView) v.findViewById(R.id.STATS_totalTime);
		final TextView accuracy  = (TextView) v.findViewById(R.id.STATS_Accuracy);
		totaldist.setText((STATS_totaldistance==0)?context.getString(R.string.unknown):(DISTANCE_FORMAT.format((float)STATS_totaldistance/1000)));
		totaltime.setText((STATS_totaltime==0)?context.getString(R.string.unknown):(IconAdapter.getTimeString(STATS_totaltime, context)));
		int acc = (int)BigPlanet.currentLocation.getAccuracy();
		accuracy.setText(""+ALTITUDE_FORMAT.format(acc));
	}
	
	public RelativeLayout getInfoWindow() {
		Log.i("TAP", "getInfoWindow");
		return infowin;
	}
	
	
	public void show() {
		// TODO show up the info window
	}
	
	
	/**
	   * 
	   * @param path
	   * @param sampleSize 1 = 100%, 2 = 50%(1/2), 4 = 25%(1/4), ...
	   * @return
	   */
	public static Bitmap getBitmapFromLocalPath(String path, int sampleSize)
	{
		try
		{
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = sampleSize;
			Log.i("UPLOAD", "decode the file of "+path);
			return BitmapFactory.decodeFile(path, options);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			Log.i("UPLOAD", "decode the file has exception");
			return null;
		} 

	}
	
    public static boolean removePhoto(String name) {
    	File file = new File(SQLLocalStorage.TRACK_PATH+"photo/"+name);
    	return file.delete();
    }
    
    public static boolean removeThumbnail(String name) {
    	File file = new File(SQLLocalStorage.TRACK_PATH+"photo/thumbnail/thumbnail"+name);
    	return file.delete();
    }
	    
	
}